package com.qinggeng.project.api.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinggeng.common.enums.ChannelTypeEnum;
import com.qinggeng.common.enums.PageTurnTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.security.service.TokenService;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.AppVersionDto;
import com.qinggeng.project.api.dto.SysActivityDTO;
import com.qinggeng.project.api.dto.SysAdverDto;
import com.qinggeng.project.api.dto.WelcomePageDto;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.utils.JsapiTicketUtils;
import com.qinggeng.project.system.domain.Shop;
import com.qinggeng.project.system.domain.SysActivity;
import com.qinggeng.project.system.domain.SysAdver;
import com.qinggeng.project.system.domain.json.DistPriceConfig;
import com.qinggeng.project.system.service.*;
import com.qinggeng.project.tool.file.domain.SysFile;
import com.qinggeng.project.tool.file.domain.json.FileConfigJson;
import com.qinggeng.project.tool.file.service.ISysFileService;
import com.qinggeng.project.tool.im.util.CheckSumBuilder;
import com.qiniu.util.Auth;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Api(tags = "配置模块")
@RestController
@RequestMapping("${apiPath}/config")
@CrossOrigin
public class ApiConfigController extends BaseController {

    @Autowired
    private ISysAdverService sysAdverService;

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private AppVersionService appVersionService;

    @Autowired
    private WelcomePageService welcomePageService;

    @Autowired
    private  TokenService tokenService;
    @Autowired
    private OrdersDistService ordersDistService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysActivityService sysActivityService;

    @ApiOperation("广告列表")
    @GetMapping("/classifyList")
    @ApiImplicitParams({
            @ApiImplicitParam(name="position",value="位置 1=首页 2=分类",dataType="Long", paramType = "query",required = false),
            @ApiImplicitParam(name="classifyId",value="所属分类id",dataType="Long", paramType = "query",required = false),
    })
    public AjaxResult adverList(
            @RequestParam(value = "position",defaultValue = "1") Long position,@RequestParam(value = "classifyId",defaultValue = "1") Long classifyId){
        SysAdver where = new SysAdver();
        where.setPositionId(position);
        where.setStatus("0");//展示状态（0=正常 1=停用）
        where.setClassifyId(classifyId);
        List<SysAdver> sysAdverList= sysAdverService.selectSysAdverList(where);
        List<SysAdverDto> sysAdverDtoList=new ArrayList<>();
        for (SysAdver adver:sysAdverList
             ) {
            SysAdverDto sysAdverDto=new SysAdverDto();
            sysAdverDto.setUrl(adver.getAdverImg());//广告图片地址
            sysAdverDto.setIsReturn(adver.getAdverType()); //跳转类型（0=不跳转，1=原生界面，2=h5页面）
            //内部链接
            if(adver.getAdverType().equals(PageTurnTypeEnum.APP.getValue())){
                sysAdverDto.setCode("1000");
                sysAdverDto.setArg(adver.getGoodsId().toString());
            }
            //外部链接（H5页面）
            if(adver.getAdverType().equals(PageTurnTypeEnum.HTML.getValue())){
                sysAdverDto.setArg(adver.getAdverHref());
            }
            sysAdverDtoList.add(sysAdverDto);
        }
        return AjaxResult.success(sysAdverDtoList);
    }

    @ApiOperation("配置信息")
    @GetMapping("/configInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name="lng",value="经度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(name="lat",value="纬度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(name="channelType",value="通道(ios,android，weixin)",dataType="String", paramType = "query",required = true),
    })
    @LoginRequired(must = false)
    public AjaxResult configInfo(Float lng,Float lat,String channelType){
        //通道验证
        ChannelTypeEnum.check(channelType);

        Map<String,Object> data = Maps.newHashMap();
        data.put("phone",configService.selectConfigByKey("sys.about.phone"));
        data.put("email",configService.selectConfigByKey("sys.about.email"));
        data.put("beian",configService.selectConfigByKey("sys.about.beian"));
        data.put("vipButton",configService.selectConfigByKey("sys.about.vipButton")!=null);
        data.put("cancelType",configService.selectConfigByKey("sys.orders.cancelType").toString().split(","));
        DistPriceConfig distPriceConfig=ordersDistService.getDistPriceConfig();
        data.put("dividePrice",distPriceConfig.getDividePrice());
        String dividePriceHint=configService.selectConfigByKey("sys.orders.dividePriceHint").toString();
        data.put("dividePriceHint",dividePriceHint.replace("dividePrice",distPriceConfig.getDividePrice().toString()));
        data.put("distPriceName",distPriceConfig.getDistPriceName());
        data.put("pickPriceName",distPriceConfig.getPickPriceName());
        //获取商户信息
        Shop shop = shopService.selectShopByLocation(lng, lat);
        data.put("shop",shop);
        //判断是否在配送范围内
        data.put("shopScope",shop.getDistance().compareTo(shop.getDistScope()) <= 0);

        //是否开启捶一捶
        return AjaxResult.success(data);
    }

    @ApiOperation("版本更新")
    @GetMapping("/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="当前版本号",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="channelType",value="通道(ios,android,ios_ggzy,android_ggzy)",dataType="String", paramType = "query",required = true)
    })
    public AjaxResult updateVersion(String version,String channelType) {
        if(StringUtils.isEmpty(version)){
            return AjaxResult.error("版本号不能为空");
        }
        if(StringUtils.isEmpty(channelType)){
            return AjaxResult.error("通道不能为空");
        }
        if(!channelType.equals(ChannelTypeEnum.IOS.getCode())
            &&!channelType.equals(ChannelTypeEnum.ANDROID.getCode())
            &&!channelType.equals(ChannelTypeEnum.IOS_GGZY.getCode())
            &&!channelType.equals(ChannelTypeEnum.ANDROID_GGZY.getCode())
        ){
            return AjaxResult.error("通道不存在");
        }
        //根据通道获取最新版本
        AppVersionDto newVersion=appVersionService.selectAppVersionDtoByType(channelType);
        if(newVersion==null){
            return AjaxResult.error("获取最新版本号失败！");
        }
        //比较版本号是否有更新
        if(appVersionService.compareVersion(version,newVersion.getVersion())){
            newVersion.setUpdate(true);
            return AjaxResult.success(newVersion);
        }
        return AjaxResult.success(new AppVersionDto(false));
    }

    @ApiOperation("微信配置")
    @GetMapping("/wxConfig")
    @CrossOrigin
    public AjaxResult wxConfig(String url)  {
        String jsapi_ticket= new JsapiTicketUtils().flushJsApiTicket();
        Map<String,String> data = new TreeMap<>();
        data.put("noncestr", StringUtils.createNoncestr(32));//随机字符串
        data.put("jsapi_ticket",jsapi_ticket);
        data.put("timestamp",String.valueOf(DateUtils.getNowDate().getTime()/1000));//时间戳
        data.put("url",url);
        StringBuffer sbkey = new StringBuffer();
        // entrySet 所有参与传参的参数按照accsii排序（升序）
        Iterator it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (StringUtils.isNotEmpty(k)) {
                sbkey.append(k + "=" + v + "&");
            }
        }
        //去除最后一位字符“&”
        String dataStrings= sbkey.toString().substring(0,sbkey.toString().length()-1);
        // 签名，需要将前面的参数加密生成
        data.put("signature", CheckSumBuilder.encode("sha1",dataStrings));
        data.put("appid", JsapiTicketUtils.APPID);
        return AjaxResult.success(data);

    }

    @ApiOperation("协议详情")
    @GetMapping("/newsInfo")
    public AjaxResult newsInfo(){
        return AjaxResult.success(appConfigService.findAppConfigById(1));
    }


    @ApiOperation("资源上传")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file)
    {
        logger.info("进入上传方法");
        try
        {
            // 上传文件路径
            SysFile sysFile = sysFileService.upload(file,true);
            Map<String,Object> data = Maps.newHashMap();
            data.put("fileName", sysFile.getRealName());
            data.put("url", sysFile.getPath());
            return AjaxResult.success(data);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 加密值
     * @return
     */
    @GetMapping("/encryptedValue")
    public AjaxResult encryptedValue(){
        String secretKey = UUID.randomUUID().toString();
        redisCache.setCacheObject("SECRET_KEY:"+secretKey,"qiuniuyun",5, TimeUnit.MINUTES);
        return AjaxResult.success(secretKey);
    }

    /**
     * 七牛云上传生成凭证
     */
    @GetMapping("/qiniuUpToken")
    @ResponseBody
    public AjaxResult QiniuUpToken(String secretKey) {
        String value = redisCache.getCacheObject("SECRET_KEY:"+secretKey);
        if (value == null){
            throw new CustomException("验证失效");
        }
        redisCache.deleteObject("SECRET_KEY:"+secretKey);
        String fileConfigJson = configService.selectConfigByKey("sys.file.config").toString();
        FileConfigJson configObject = JSON.parseObject(fileConfigJson, FileConfigJson.class);
        // 构造一个带指定Zone对象的配置类
        Auth auth = Auth.create(configObject.getAccessKey(), configObject.getSecretKey());
        String upToken = auth.uploadToken(configObject.getBucket());
        Map<String,String> data = new HashMap<>();
        data.put("upToken",upToken);

        return AjaxResult.success(data);
    }

    @ApiOperation("资源批量上传")
    @PostMapping("/uploadBatch")
    public AjaxResult uploadBatch(MultipartFile [] file)
    {
        try
        {
            List<Map<String,Object>> uploadUrls = Lists.newArrayList();
            Map<String,Object> data = null;
            for (MultipartFile multipartFile : file) {
                // 上传文件路径
                SysFile sysFile = sysFileService.upload(multipartFile,true);
                data = Maps.newHashMap();
                data.put("fileName", sysFile.getRealName());
                data.put("url", sysFile.getPath());
                uploadUrls.add(data);
            }
            return AjaxResult.success(uploadUrls);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("欢迎页图片")
    @GetMapping("/welcomePage")
    @ApiResponses({
            @ApiResponse(code = 200,message = "",response = WelcomePageDto.class)
    })
    public AjaxResult welcomePage(){
        WelcomePageDto welcomePageDto = WelcomePageDto.getWelcomePageDto(welcomePageService.selectWelcomePage());
        return AjaxResult.success(welcomePageDto);
    }

    @ApiOperation("活动列表")
    @GetMapping("/activity")
    public AjaxResult activity(){
        return AjaxResult.success(sysActivityService.listSysActivityDTO());
    }
}
